<template>
  <div class="system-settings">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 基本设置 -->
      <el-tab-pane label="基本设置" name="basic">
        <el-divider />
        <el-form :model="userInfo" label-width="120px" class="settings-form">
          <el-form-item label="系统名称">
            <el-input v-model="userInfo.systemName" />
          </el-form-item>
          <el-form-item label="管理员昵称">
            <el-input v-model="userInfo.username" disabled/>
          </el-form-item>
          <el-form-item label="管理员邮箱">
            <el-input v-model="userInfo.email" disabled />
          </el-form-item>
        </el-form>
        <div class="settings-footer">
          <el-button type="primary" @click="handleSave">保存设置</el-button>
        </div>
      </el-tab-pane>

      <!-- API配置 -->
      <el-tab-pane label="API配置" name="api">
        <el-divider />

        <div class="api-list">
          <div class="table-header">
            <el-button type="primary" @click="handleAdd">新增API</el-button>
            <el-button
                type="danger"
                :disabled="!selectedRows.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
            <el-button type="primary" link @click="handleSyncAllQuota" style="float:right;">
              <el-icon><Refresh /></el-icon>
              同步所有配额
            </el-button>
          </div>

          <el-table
              v-loading="loading"
              :data="apiKeys"
              @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="expand">
              <template #default="props">
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户邮箱">
                    {{ props.row.email }}
                  </el-descriptions-item>
                  <el-descriptions-item label="错误信息" v-if="props.row.errorMessage">
                    <el-tag type="danger">{{ props.row.errorMessage }}</el-tag>
                  </el-descriptions-item>
                </el-descriptions>
              </template>
            </el-table-column>
            <el-table-column label="API密钥" prop="apiKey" show-overflow-tooltip />
            <el-table-column label="回调地址" prop="callbackUrl" show-overflow-tooltip />
            <el-table-column label="剩余配额" prop="remainingQuota" width="100" />
            <el-table-column label="创建时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="primary" link @click="handleSyncQuota(row)">同步配额</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              class="pagination"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
          />
        </div>

        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'add' ? '新增API' : '编辑API'"
            width="500px"
            destroy-on-close
        >
          <el-form
              ref="apiFormRef"
              :model="apiForm"
              :rules="apiFormRules"
              label-width="100px"
          >
            <el-form-item label="API密钥" prop="apiKey">
              <el-input
                  v-model="apiForm.apiKey"
                  :disabled="dialogType === 'edit'"
                  type="password"
                  placeholder="请输入API密钥"
              />
            </el-form-item>
            <el-form-item label="回调地址" prop="callbackUrl">
              <el-input
                  v-model="apiForm.callbackUrl"
                  placeholder="请输入回调地址"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit" v-loading="loading">确定</el-button>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { useSystemStore } from '@/stores/system'
import { formatDateTime } from '@/utils/date'

const systemStore = useSystemStore()
const activeTab = ref('basic')
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])
const apiFormRef = ref(null)

// 计算属性
const total = computed(() => systemStore.total)
const apiKeys = computed(() => systemStore.apiKeys)

const userInfo = ref({
  systemName: '',
  username: '',
  email: ''
})

const apiForm = ref({
  apiKey: '',
  callbackUrl: ''
})

const apiFormRules = {
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' },
    { min: 32, message: 'API密钥长度不能小于32个字符', trigger: 'blur' }
  ],
  callbackUrl: [
    { required: true, message: '请输入回调地址', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    loadSystemInfo(),
    loadApiKeys()
  ])
})

// 加载系统信息
async function loadSystemInfo() {
  try {
    await systemStore.getSystemInfo()
    userInfo.value = systemStore.systemInfo
  } catch (error) {
    ElMessage.error('加载系统信息失败')
  }
}

// 加载API密钥列表
async function loadApiKeys() {
  loading.value = true
  try {
    await systemStore.getApiKeys({
      current: currentPage.value,
      size: pageSize.value
    })
  } catch (error) {
    ElMessage.error('加载API列表失败')
  } finally {
    loading.value = false
  }
}

// 保存系统设置
async function handleSave() {
  try {
    const data = {
      systemName: userInfo.value.systemName,
    }
    await systemStore.updateSystemInfo(data)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 同步单个API配额
async function handleSyncQuota(row) {
  try {
    loading.value = true
    const quota = await systemStore.getApiKeyQuota(row.id)
    row.remainingQuota = quota.data.remaining_quota
    ElMessage.success('同步成功')
  } catch (error) {
    ElMessage.error('同步失败')
  }finally {
    loading.value = false
  }
}

// 同步所有API配额
async function handleSyncAllQuota() {
  try {
    loading.value = true
    const promises = apiKeys.value.map(api => systemStore.getApiKeyQuota(api.id))
    await Promise.all(promises)
    await loadApiKeys()
    ElMessage.success('所有配额同步成功')
  } catch (error) {
    ElMessage.error('配额同步失败')
  }finally {
    loading.value = false
  }
}

// 新增API
function handleAdd() {
  dialogType.value = 'add'
  apiForm.value = {
    apiKey: '',
    callbackUrl: ''
  }
  dialogVisible.value = true
}

// 编辑API
function handleEdit(row) {
  dialogType.value = 'edit'
  apiForm.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
async function handleSubmit() {
  if (!apiFormRef.value) return

  try {
    await apiFormRef.value.validate()

    loading.value = true
    if (dialogType.value === 'add') {
      await systemStore.addApiKey(apiForm.value)
      ElMessage.success('添加成功')
    } else {
      await systemStore.updateApiKey(apiForm.value.id, apiForm.value)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    loadApiKeys()
  } catch (error) {
    if (error === false) return
    ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
  }finally {
    loading.value = false
  }
}

// 删除API
async function handleDelete(row) {
  try {
    await ElMessageBox.confirm('确认删除该API密钥？', '提示', {
      type: 'warning'
    })
    loading.value = true
    await systemStore.deleteApiKey(row.id)
    ElMessage.success('删除成功')
    if (apiKeys.value.length === 1 && currentPage.value > 1) {
      currentPage.value--
    }
    loadApiKeys()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }finally {
    loading.value = false
  }
}

// 批量删除
async function handleBatchDelete() {
  try {
    loading.value = true
    await ElMessageBox.confirm(
        `确认删除选中的${selectedRows.value.length}个API密钥？`,
        '提示',
        { type: 'warning' }
    )
    const ids = selectedRows.value.map(row => row.id)
    await systemStore.batchDeleteApiKeys(ids)
    ElMessage.success('删除成功')
    selectedRows.value = []
    loadApiKeys()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }finally {
    loading.value = false
  }
}

// 表格选择变化
function handleSelectionChange(rows) {
  selectedRows.value = rows
}

// 页码变化
function handlePageChange(page) {
  currentPage.value = page
  loadApiKeys()
}

// 每页条数变化
function handleSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  loadApiKeys()
}
</script>

<style scoped>
.system-settings {
  padding: 20px;
}

.quota-card {
  max-width: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.settings-form {
  max-width: 600px;
  margin: 20px 0;
}

.settings-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #dcdfe6;
}
</style>